package com.oschina.basic.io;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class MyFileIO {

	private String	file;
	private String	charSet;

	public MyFileIO(String file, String charSet) {
		this.file = file;
		this.charSet = charSet;
	}

	public void write(String file, String content) throws IOException {
		try {
			FileOutputStream out = new FileOutputStream(file);
			OutputStreamWriter writer = new OutputStreamWriter(out, charSet);

			try {
				writer.write(content);
			} finally {
				writer.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public String read(String file) throws IOException {
		char[] buf = new char[64];
		StringBuilder result = new StringBuilder();
		try {
			FileInputStream in = new FileInputStream(file);
			InputStreamReader reader = new InputStreamReader(in, charSet);
			try {

				while ((reader.read(buf)) != -1) {

					result.append(buf);
				}
			} finally {
				reader.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result.toString();
	}

	public String merge(String fileA, String fileB, String fileC) throws IOException {

		String contentA = read(fileA);
		String contentB = read(fileB);
		if (contentA == null || contentA.length() == 0) {
			write(fileC, contentB);
		}

		if (contentB == null || contentB.length() == 0) {
			write(fileC, contentA);
		}
		String[] arrayA = contentA.split("\n");
		String[] arrayB = contentB.split("\n");
		List<String> c = new LinkedList<String>();
		int i = 0;
		for (i = 0; (i < arrayB.length) && (i < arrayA.length); i++) {
			c.add(arrayA[i]);
			c.add(arrayB[i]);
		}
		for (; i < arrayB.length; i++) {
			c.add(arrayB[i]);
		}
		for (; i < arrayA.length; i++) {
			c.add(arrayA[i]);
		}
		write(fileC, Arrays.toString(c.toArray(new String[c.size()])));
		return Arrays.toString(c.toArray(new String[c.size()]));


	}
}

